<!--  -->
<template>
  <div class="zzr_form_components">
    <el-form
      ref="zzrForm"
      :model="buildFormData"
      :label-position="labelPosition"
      :label-width="labelWidth + 'px'"
      :size="formSize"
      :disabled="disabled"
    >
      <div v-for="(item, index) in buildFormData.form" :key="index" :class="`zzr_form_item zzr_form_item_${item.size || 'normal'}`"
        v-show="item._show"
      >
        <!-- 文本域 -->
        <el-form-item
          v-if="item.type == 'text'"
          :label="item.label"
          :prop="`form.${index}.value`"
          :rules="item.rules"
        >
          <el-input
            v-model="item.value"
            :disabled="item.disabled"
            type="text"
            :placeholder="item.placeholder"
          ></el-input>
        </el-form-item>
        <!-- textarea -->
        <el-form-item
          v-if="item.type == 'textarea'"
          :label="item.label"
          :prop="`form.${index}.value`"
          :rules="item.rules"
        >
          <el-input
            v-model="item.value"
            :disabled="item.disabled"
            type="textarea"
            :placeholder="item.placeholder"
            :autosize="{minRows:2}"
          ></el-input>
        </el-form-item>
        <!-- 密码域 -->
        <el-form-item
          v-if="item.type == 'password'"
          :label="item.label"
          :prop="`form.${index}.value`"
          :rules="item.rules"
        >
          <el-input
            v-model="item.value"
            :disabled="item.disabled"
            type="password"
            :placeholder="item.placeholder"
          ></el-input>
        </el-form-item>
        <!-- 基础下拉框 -->
        <el-form-item
          v-if="item.type == 'select'"
          :label="item.label"
          :prop="`form.${index}.value`"
          :rules="item.rules"
        >
          <el-select
            v-model="item.value"
            :placeholder="item.placeholder"
            :collapse-tags="item.collapseTags"
            :filterable="item.filterable"
            :multiple="item.multiple"
            clearable
          >
            <el-option
              v-for="idt in item.options"
              :disabled="idt.disabled"
              :key="idt.value"
              :label="idt.label"
              :value="idt.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 级联下拉框 -->
        <el-form-item
          v-if="item.type == 'cascader'"
          :label="item.label"
          :prop="`form.${index}.value`"
          :rules="item.rules"
        >
          <el-cascader
            v-model="item.value"
            :placeholder="item.placeholder"
            :options="item.options"
            :props="item.config"
            :filterable="item.filterable"
            :collapse-tags="item.collapseTags"
            clearable
          >
          </el-cascader>
        </el-form-item>
        <!-- 时间选择器 -->
        <el-form-item
          v-if="item.type == 'timePicker'"
          :label="item.label"
          :prop="`form.${index}.value`"
          :rules="item.rules"
        >
          <el-time-picker
            v-model="item.value"
            :is-range="item.isRange"
            :placeholder="item.placeholder"
            :value-format="item.valueFormat|| 'hh:mm:ss'"
            :format="item.format"
            :picker-options="item.selectableRange">
          </el-time-picker>
        </el-form-item>
        <!-- 日期选择器 -->
        <el-form-item
          v-if="item.type == 'datePicker'"
          :label="item.label"
          :prop="`form.${index}.value`"
          :rules="item.rules"
        >
        <el-date-picker
          v-model="item.value"
          :type="item.dateType"
          value-format="yyyy-MM-dd"
          unlink-panels
          :placeholder="item.placeholder">
        </el-date-picker>
        </el-form-item>
        <!-- 时间日期选择器 -->
        <el-form-item
          v-if="item.type == 'dateTimePicker'"
          :label="item.label"
          :prop="`form.${index}.value`"
          :rules="item.rules"
        >
        <el-date-picker
          v-model="item.value"
          :type="item.dateType"
          :value-format="item.valueFormat ||'yyyy-MM-dd HH:mm:ss'"
          :format="item.valueFormat"
          :placeholder="item.placeholder">
        </el-date-picker>
        </el-form-item>
        <!-- 文件上传 -->
        <el-form-item
          v-if="item.type == 'upload'"
          :label="item.label"
          :prop="`form.${index}.value`"
          :rules="item.rules"
        >
        <span slot="label"  v-if="item.slotlabel" v-html="item.slot"></span >
        <zzrNormalUpload v-model="item.value" :limit="item.limit" :imgUrl="item.imgUrl" :viewOnly="item.viewOnly"></zzrNormalUpload>
        <!-- <el-date-picker
          v-model="item.value"
          :type="item.dateType"
          value-format="yyyy-MM-dd hh:mm:ss"
          :placeholder="item.placeholder">
        </el-date-picker> -->
        </el-form-item>
      </div>
    </el-form>
    <div class="zzr_form_btn_group" v-if="!disabled">
        <el-button type="primary" :loading="submitLoading" @click="submit('zzrForm')">{{$t('message.btnUpdate')}}</el-button>
    </div>
  </div>
</template>

<script>
/*
  @description 自动化表单
  @param {Array} formGroup 表单组结构
  @param {
    type:[String] 类型,
    label:[String] 名称,
    name:[String] 属性,
    value:[String,Number] 属性值,
    disabled:[Boolean] 是否禁用,
    placeholder:[String] 提示文字,
    required:[Boolean] 是否必填,
    rules:[Array] 验证规则,
    filterable:[Boolean] 是否带清除(输入框无效),
    options:[Array] 下拉选项
    collapseTags:[Boolean] 是否折叠多选槽
    config:[Object] 控件配置项
  }
*/
import dataFormat  from '@/utils/formDateBuild'
import zzrNormalUpload from '@/components/zzrFormTrends/zzrNormalUpload'
export default {
    name:'zzrFormTrends',
    components:{zzrNormalUpload},
    props:{
        labelWidth:{
            type:Number,
            default:80
        },
        labelPosition:{
            type:String,
            default:'top'
        },
        formSize:{
            type:String,
            default:'medium'
        },
        disabled:{
            type:Boolean,
            default:false
        },
        formData:{
          type:Object,
          default:()=>{}
        },
        onSubmit:Function
    },
    data(){
        return{
          hidden:false,
          submitLoading:false,
          buildFormData:{}
        }
    },
    //生命周期 - 创建完成（可以访问当前this实例）
    created() {
        this.submitLoading = this.formData.formConfig.loading || false
        this.getForm()
    },
    computed:{
      formBaseData(){
        return dataFormat.returnData(this.buildFormData.form)
      }
    },
    watch:{
      formData:{
        handler(oldValue,newValus){       
          if(newValus){        
            let form = newValus.form;
            newValus.form.map((item,index)=>{
              if(typeof item.show=='function'){
                this.$set(item,'_show',item.show(form))
              }
              if(typeof item.yzrules=='function'&&JSON.stringify(item.rules)!=JSON.stringify(item.yzrules(form))){
                this.$set(item,'rules',item.yzrules(form))
              }
            })
          }
        },
        deep:true
      }
    },
    methods:{
      //form初始化
      getForm(){
        let formBase = {...this.formData};
        var form = formBase.form;
        form.forEach(filed=>{
          if(filed.type=='text' || filed.type=='textarea' || filed.type=='password'){
            this.$set(filed,'placeholder',this.$t('message.plsInput',{name:filed.label}))
          }else if(filed.type=='select' || filed.type=='datePicker' || filed.type=='dateTimePicker' || filed.type=='cascader' || filed.type=='timePicker'){
            this.$set(filed,'placeholder',this.$t('message.plsSelect',{name:filed.label}))
          }
          if(filed.ajaxConfig){
            let data = [];
            this.$api.get(filed.ajaxConfig.url,filed.ajaxConfig.data||{}).then(res=>{
              data = res[filed.ajaxConfig.data.ptypes];
              this.$set(filed,'options',data);
            }).catch(e=>{});
          }
          if(typeof filed.show=='function'){
            this.$set(filed,'_show',filed.show(form))
          }else{
            if(filed.show!==undefined){
              this.$set(filed,'_show',filed.show)
            }else{
              this.$set(filed,'_show',true)
            }
          }
          if(typeof filed.yzrules=='function'){
            this.$set(filed,'rules',filed.yzrules(form))
          }else{
            if(filed.show!==undefined){
              this.$set(filed,'rules',filed.yzrules)
            }
          }
        });
        formBase.form = form;
        this.buildFormData =  formBase;
      },
      submit(formName){
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$emit('onSubmit',dataFormat.returnData(this.buildFormData.form))
            //this.onSubmit(dataFormat.returnData(this.buildFormData.form))
          } else {
            //console.log('error submit!!');
            return false;
          }
        });
      },
      setFormRules(data){
        for(let i in this.buildFormData.form){
          for(let j in data){
            if(this.buildFormData.form[i].name == j){
              this.buildFormData.form[i].value = data[j]
            }
          }
        }
      },
      resetForm(formName){
        this.$refs[formName].resetFields();
      },
    },
    //生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {},
    beforeCreate() {}, //生命周期 - 创建之前
    beforeMount() {}, //生命周期 - 挂载之前
    beforeUpdate() {}, //生命周期 - 更新之前
    updated() {}, //生命周期 - 更新之后
    beforeDestroy() {}, //生命周期 - 销毁之前
    destroyed() {}, //生命周期 - 销毁完成
    activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style lang='stylus' scoped>
.zzr_form_components
   .el-form
    display flex
    flex-wrap wrap
    .zzr_form_item
      min-width 130px
      .el-form-item
        padding 0 10px
        margin 10px 0
        .el-cascader__tags .el-tag
          max-width 70%
        >>>.el-textarea__inner
          resize none
      >>>.el-cascader,.el-select
          display block
      >>>.el-range-editor.el-input__inner,.el-date-editor.el-input
          width 100%
      &.zzr_form_item_normal
        width 100%  
      &.zzr_form_item_midum
        width 50%
      &.zzr_form_item_mini
        width 25%
      &.zzr_form_item_big
        width 75%  
.el-form::before,.el-form::after
  content ''
  display block
  clear both
.zzr_form_btn_group
  position absolute
  bottom 15px
  left 0
  right 0
  text-align center
</style>